package com.netty.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;


/**
 * @author renyitong
 * @version 1.0.0
 * @createTime 2023年08月16日
 * @Description 心跳计数挤下s
 * 若连续2次无读写事件，则关闭这个客户端channel
 */
@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    private int readLossConnectCount = 0;
    private int writeLossConnectCount = 0;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg.equals("ping")) {
            ctx.channel().writeAndFlush("pong");
        } else {
            // 由下一个handler处理
            ctx.channel().writeAndFlush(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
                writeLossConnectCount++;
                if (writeLossConnectCount > 2) {
                    log.info(" 已经20s没【写】操作了,好寂寞,我关闭了...");
                    ctx.channel().close();
                }
            } else if (event.state() == IdleState.READER_IDLE) {
                readLossConnectCount++;
                if (readLossConnectCount > 2) {
                    log.info(" 已经20s没【读】操作了,好寂寞,我关闭了...");
                    ctx.channel().close();
                }
            }

        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
